import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useUserProfile } from '@/hooks/useUserProfile';
import VoiceInputButton from '../../../../components/VoiceInput/VoiceInputButton';
import TokenInsufficientModal from '../../../../components/TokenInsufficientModal';
import useIsMobile from '../../../../hooks/isMoboile';
import { AudioCompatibility } from '../../../../utils/audioUtils';
import { ImageService } from '../../../../api/imageService';
import { request } from '@/api/request';
import { refreshTokenBalance } from '@/components/TokenBalance';
import { getDynamicFonts } from '@/utils/fontUtils';
import closeVoiceIcon from '@/assets/images/chatPage/closeVoice.webp'//关闭语音图标
import openVoiceIcon from '@/assets/images/chatPage/openVoice.webp'//开启语音图标

/**
 * 消息输入组件
 * 功能：处理用户消息输入，支持文本和语音模式，包含图片生成功能
 * 特性：
 * - 多模式输入：支持文本输入和语音录音
 * - 图片生成：集成AI图片生成功能，支持快捷提示词
 * - Token管理：检查用户Token余额，不足时显示购买弹窗
 * - 响应式设计：移动端和桌面端不同的交互方式
 * - 性能优化：使用useCallback和React.memo减少重渲染
 * - 教程引导：提供图片生成使用说明弹窗
 * - 内存安全：支持组件卸载时取消异步操作
 */

interface MessageInputProps {
  onSendMessage: (content: string, isVoice: boolean) => void;
  disabled?: boolean;
  // isVoiceMode: boolean;
  setWaitingForAIReply?: (waiting: boolean) => void;
  // 新增：直接向聊天窗口添加消息而不发送API请求的函数
  onAddLocalMessage?: (message: any) => void;
  onMbtiClick?: () => void; // 新增
}

// 图片生成选项
const getImageGenerationOptions = (t: any) => [
  t('chat.messageInput.imageGeneration.showMe'),
  t('chat.messageInput.imageGeneration.sendMe'),
  t('chat.messageInput.imageGeneration.canISee')
];
// 教程弹窗组件 , dropdownRef 
const HowToUseModal: React.FC<{ show: boolean; onClose: () => void; dropdownRef: React.RefObject<HTMLDivElement> }> = ({ show, onClose }) => {
  const { t, i18n } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);
  const [currentStep, setCurrentStep] = useState(1);
  const isMobile = useIsMobile();
  if (!show) return null;
  // 教程弹窗 事件
  const handleNext = (e: React.MouseEvent) => {
    e.stopPropagation();
    setCurrentStep(2);
  };
  // 教程弹窗 事件
  const handlePrev = (e: React.MouseEvent) => {
    e.stopPropagation();
    setCurrentStep(1);
  };
  // 教程弹窗 事件
  const handleGotIt = (e: React.MouseEvent) => {
    e.stopPropagation();
    setCurrentStep(1);
    onClose(); // 只关闭教程弹窗，不关闭下拉框
  };

  // 教程弹窗
  return (
    <div
      className={
        isMobile
          ? "fixed left-[2vw] right-[2vw] bottom-[65px] z-[100]"
          : "absolute bottom-full left-[-11rem] mb-2 z-[100]"
      }
      onClick={(e) => e.stopPropagation()}
    >
      <div
        className={`bg-gray-800 rounded-xl flex flex-col shadow-xl border border-gray-600 ${isMobile ? 'w-[96vw]' : 'w-80 '
          }`}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-700">
          <div className="flex items-center space-x-2">
            <i className="fas fa-question-circle text-pink-500"></i>
            <span style={{ fontFamily: dynamicFonts.font3 }} className="text-white text-[1.2rem] font-medium">{t('chat.messageInput.howToUseModal.title')}</span>
          </div>
          <button
            onClick={(e) => {
              e.stopPropagation();
              onClose();
            }}
            className="text-gray-400 hover:text-white transition-colors p-1"
          >
            <i className="fas fa-times"></i>
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 p-4 overflow-y-auto custom-scrollbar-thin">
          {currentStep === 1 ? (
            <div className="space-y-4">
              <h3 className="text-white text-lg font-semibold">
                {t('chat.messageInput.howToUseModal.howToPromptForImages')}
              </h3>
              <p className="text-pink-400">
                {t('chat.messageInput.howToUseModal.startYourRequest')}
              </p>
              <ul>
                <li className="text-pink-400">• {t('chat.messageInput.imageGeneration.sendMe')}...</li>
                <li className="text-pink-400">• {t('chat.messageInput.imageGeneration.showMe')}...</li>
                <li className="text-pink-400">• {t('chat.messageInput.imageGeneration.canISee')}...</li>
                {/* <li className="text-pink-400">• Send...</li> */}
              </ul>
            </div>
          ) : (
            <div className="space-y-4">
              <h3 className="text-white text-lg font-semibold">
                {t('chat.messageInput.howToUseModal.completeTheSentence')}
              </h3>
              <p className="text-pink-400">{t('chat.messageInput.howToUseModal.examples')}</p>
              <ul>
                <li className="text-pink-400">• {t('chat.messageInput.howToUseModal.example1')}</li>
                <li className="text-pink-400">• {t('chat.messageInput.howToUseModal.example2')}</li>
                <li className="text-pink-400">• {t('chat.messageInput.howToUseModal.example3')}</li>
              </ul>
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{ fontFamily: dynamicFonts.font3 }} className="flex items-center justify-between p-4 border-t border-gray-700">
          <span className="text-[white] text-sm">
            {t('chat.messageInput.howToUseModal.step')} {currentStep} {t('chat.messageInput.howToUseModal.of')} 2
          </span>
          <div className="flex space-x-2">
            {currentStep === 1 ? (
              <button
                onClick={handleNext}
                className="bg-pink-500 hover:bg-pink-600 text-white px-4 py-2 rounded-lg transition-colors"
              >
                {t('chat.messageInput.howToUseModal.next')}
              </button>
            ) : (
              <>
                <button
                  onClick={handlePrev}
                  className="bg-gray-600 hover:bg-gray-500 text-white px-4 py-2 rounded-lg transition-colors"
                >
                  {t('chat.messageInput.howToUseModal.prev')}
                </button>
                <button
                  onClick={handleGotIt}
                  className="bg-pink-500 hover:bg-pink-600 text-white px-4 py-2 rounded-lg transition-colors"
                >
                  {t('chat.messageInput.howToUseModal.gotIt')}
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

/**
 * 消息输入组件
 * 支持文本输入和语音模式显示
 * 优化版本：使用useCallback和React.memo减少重渲染，添加异步操作取消机制
 */
const MessageInput: React.FC<MessageInputProps> = React.memo(({
  onSendMessage,
  disabled = false,
  // isVoiceMode,
  setWaitingForAIReply,
  onAddLocalMessage,
  onMbtiClick
}) => {
  const { t, i18n } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);
  const [inputValue, setInputValue] = useState('');
  const [isFocused, setIsFocused] = useState(false);
  const [isVoiceMode, setIsVoiceMode] = useState(false); // 语音模式状态
  const [isVoiceInputMode, setIsVoiceInputMode] = useState(false); // 新增：语音输入模式状态
  const [permissionError, setPermissionError] = useState<string | null>(null); // 新增：权限错误状态
  const [showDropdown, setShowDropdown] = useState(false); // 下拉菜单显示状态
  const [showHowToUseModal, setShowHowToUseModal] = useState(false); // 教程弹窗显示状态
  const [isImageGenerationMode, setIsImageGenerationMode] = useState(false); // 跟踪是否为图片生成模式
  const [originalPrompt, setOriginalPrompt] = useState(''); // 存储原始提示词
  // Token不足弹窗状态
  const [showTokenModal, setShowTokenModal] = useState(false);
  const [tokenModalData, setTokenModalData] = useState<{
    currentBalance: number;
    required: number;
    serviceType: 'text' | 'voice' | 'img';
  }>({ currentBalance: 0, required: 0, serviceType: 'img' });
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const isMobile = useIsMobile(); // 检测是否为移动端
  const isUnmountedRef = useRef(false); // 新增：组件卸载标记，用于取消异步操作
  // 从sessionStorage获取当前对话ID
  const [aiPersonId, setAiPersonId] = useState<string | undefined>(() => {
    return sessionStorage.getItem('currentConversationId') || undefined;
  });

  // 监听sessionStorage变化
  useEffect(() => {
    const handleStorageChange = () => {
      const newId = sessionStorage.getItem('currentConversationId');
      setAiPersonId(newId || undefined);
    };

    // 监听storage事件（跨标签页的变化）
    window.addEventListener('storage', handleStorageChange);
    
    // 定期检查sessionStorage变化（同标签页内的变化）
    const interval = setInterval(handleStorageChange, 100);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      clearInterval(interval);
    };
  }, []);
  const { userData } = useUserProfile();
  const IMAGE_GENERATION_OPTIONS = useMemo(() => getImageGenerationOptions(t), [t]); // 获取图片生成选项
  const imageServiceRef = useRef<ImageService | null>(null);// 创建图片生成服务实例
  // 处理焦点状态 - 使用useCallback优化
  const handleFocus = useCallback(() => setIsFocused(true), []);
  const handleBlur = useCallback(() => setIsFocused(false), []);

  // 组件卸载时设置标记
  useEffect(() => {
    return () => {
      isUnmountedRef.current = true;
    };
  }, []);


  // 所有选项
  const DROPDOWN_OPTIONS = useMemo(() => [
    ...IMAGE_GENERATION_OPTIONS,
    t('chat.messageInput.imageGeneration.howToUse')
  ], [IMAGE_GENERATION_OPTIONS, t]);

  // 自动调整输入框高度 - 使用useCallback优化
  const adjustTextareaHeight = useCallback(() => {
    const textarea = textareaRef.current;
    if (textarea) {
      textarea.style.height = 'auto';
      const maxHeight = 120; // 最大高度
      const newHeight = Math.min(textarea.scrollHeight, maxHeight);
      textarea.style.height = `${newHeight}px`;
    }
  }, []);

  // 处理输入变化 - 使用useCallback优化
  const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newValue = e.target.value;
    setInputValue(newValue);

    // 检查是否清除了图片生成模式的提示词
    if (isImageGenerationMode && originalPrompt) {
      const hasOriginalPrompt = IMAGE_GENERATION_OPTIONS.some(option =>
        newValue.startsWith(option)
      );

      if (!hasOriginalPrompt) {
        // 用户清除了图片生成提示词，切换回普通聊天模式
        setIsImageGenerationMode(false);
        setOriginalPrompt('');
        // console.log('🖼️ 用户清除了图片生成提示词，切换回聊天模式');
      }
    }

    adjustTextareaHeight();
  }, [adjustTextareaHeight, isImageGenerationMode, originalPrompt, IMAGE_GENERATION_OPTIONS]);

  // 初始化ImageService
  useEffect(() => {
    // 如果用户数据中有令牌，则使用令牌初始化ImageService
    if (userData?.visitor_token) {
      if (!imageServiceRef.current) {
        imageServiceRef.current = new ImageService(userData.visitor_token, aiPersonId);
      } else {
        imageServiceRef.current.setToken(userData.visitor_token);
        imageServiceRef.current.setAiPersonId(aiPersonId || '');
      }
    } else if (!imageServiceRef.current) {
      // 如果没有令牌，仍然需要初始化ImageService
      imageServiceRef.current = new ImageService(undefined, aiPersonId);
    }

    // 设置翻译函数，确保ImageService支持国际化
    if (imageServiceRef.current) {
      imageServiceRef.current.setTranslationFunction(t);
    }
  }, [userData?.visitor_token, t, aiPersonId]);

  // 直接添加消息到聊天界面而不发送请求
  const addLocalMessage = useCallback((message: any) => {
    if (onAddLocalMessage) {
      onAddLocalMessage(message);
    } else {
      // console.warn('🖼️ onAddLocalMessage 未提供，无法本地添加消息');
      console.error('onAddLocalMessage is not provided, cannot add message locally');
    }
  }, [onAddLocalMessage]);

  // 保存图片到正确的聊天历史中（当页面切换或组件卸载时使用）
  const saveImageToCorrectChatHistory = useCallback(async (taskResult: any, targetAiPersonId: string, messageId: string) => {
    try {
      if (!taskResult.image_url || !targetAiPersonId) {
        // console.warn('🔄 无效的图片结果或AI ID，跳过保存');
        console.error('invalid image result or AI ID, skip save');
        return;
      }

      // console.log('🔄 保存图片到正确的聊天历史:', {
      //   aiPersonId: targetAiPersonId,
      //   imageUrl: taskResult.image_url,
      //   messageId
      // });

      // 创建图片消息对象
      const imageMessage = {
        id: messageId,
        type: 'image',
        content: '生成的图片',
        sender: 'ai',
        timestamp: Date.now(),
        status: 'completed',
        imageUrl: taskResult.image_url,
        receivedAt: Date.now(),
        isImageGenerating: true
      };

      // 获取正确的聊天历史
      const chatHistoryKey = `chat_history_${targetAiPersonId}`;
      let chatHistory: any = { messages: [] };

      try {
        const stored = localStorage.getItem(chatHistoryKey);
        if (stored) {
          chatHistory = JSON.parse(stored);
        }
      } catch (e) {
        // console.error('获取聊天历史失败:', e);
        console.error('get chat history failed', e);
      }

      // 检查是否已存在相同ID的消息（可能是loading消息）
      const existingIndex = chatHistory.messages.findIndex((msg: any) => msg.id === messageId);
      if (existingIndex >= 0) {
        // 更新现有消息
        chatHistory.messages[existingIndex] = imageMessage;
        // console.log('🔄 更新现有loading消息为图片消息');
      } else {
        // 添加新消息
        chatHistory.messages.push(imageMessage);
        // console.log('🔄 添加新图片消息到聊天历史');
      }

      // 保存更新后的聊天历史
      localStorage.setItem(chatHistoryKey, JSON.stringify(chatHistory));

      // console.log('✅ 图片已保存到正确的聊天历史:', {
      //   aiPersonId: targetAiPersonId,
      //   messageId
      // });

      // 🔔 触发聊天历史更新事件，通知相关组件刷新
      const event = new CustomEvent('chat-history-update', {
        detail: {
          chatId: targetAiPersonId,
          newMessage: imageMessage,
          timestamp: Date.now(),
          source: 'MessageInput'
        }
      });
      window.dispatchEvent(event);

    } catch (error) {
      // console.error('🔄 保存图片到聊天历史失败:', error);
      console.error('save image to chat history failed', error);
    }
  }, []);

  // Token预留结果接口
  interface TokenReservationResult {
    success: boolean;
    reserve_id?: string;
    reserved?: number;
    expires_at?: string;
    balance_after?: number;
    message?: string;
    // 错误情况
    error?: string;
    current_balance?: number;
    required?: number;
  }

  // 预留图片生成tokens
  const reserveTokensForImage = useCallback(async (): Promise<string> => {
    try {
      // 从localStorage获取用户数据
      const userDataStr = localStorage.getItem('userData');
      if (!userDataStr) {
        throw new Error('用户数据不存在，无法预留tokens');
      }

      const userData = JSON.parse(userDataStr);
      const userUuid = userData.visitor_uuid;

      if (!userUuid) {
        throw new Error('用户UUID不存在，无法预留tokens');
      }

      const apiBaseUrl = (() => {
        const { hostname, protocol } = window.location;
        if (import.meta.env.VITE_NODE_API_BASE_URL) {
          return import.meta.env.VITE_NODE_API_BASE_URL;
        }
        if (hostname !== 'localhost' && hostname !== '127.0.0.1') {
          return `${protocol}//${hostname}:8000`;
        }
        return 'http://127.0.0.1:8000';
      })();
      const url = `${apiBaseUrl}/api/tokens/reserve`;

      // console.log('🪙 开始预留图片生成tokens:', {
      //   userUuid,
      //   serviceType: 'img',
      //   url
      // });

      // 准备请求头
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      };

      // 如果有token，添加到请求头
      if (userData?.visitor_token) {
        headers['Authorization'] = `Bearer ${userData.visitor_token}`;
      }

      // 发送预留请求
      const response = await fetch(url, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          user_uuid: userUuid,
          service_type: 'img',
          amount: 5
        })
      });

      const result: TokenReservationResult = await response.json();

      if (!response.ok) {
        // console.error(`❌ 图片生成Token预留失败: HTTP ${response.status}`, result);
        console.error(`image token reservation failed: HTTP ${response.status}`, result);

        // 检查是否是余额不足错误
        if (result.error === 'Insufficient tokens' && result.current_balance !== undefined && result.required !== undefined) {
          // 抛出特殊的余额不足错误，包含详细信息
          const error = new Error('Insufficient tokens') as any;
          error.isInsufficientTokens = true;
          error.currentBalance = result.current_balance;
          error.required = result.required;
          error.serviceType = 'img';
          throw error;
        }

        throw new Error(result.error || `图片生成Token预留失败: ${response.status}`);
      }

      // console.log('✅ 图片生成Token预留成功:', result);

      if (!result.success || !result.reserve_id) {
        throw new Error(result.message || '图片生成Token预留失败: 未获取到reserve_id');
      }

      // 预留成功后，触发余额刷新
      setTimeout(() => {
        refreshTokenBalance();
      }, 500); // 延迟500ms后刷新余额，给服务器处理时间

      return result.reserve_id;

    } catch (error) {
      // console.error('❌ 图片生成Token预留出错:', error);
      console.error('image token reservation failed', error);
      throw error;
    }
  }, []);

  // 处理图片生成请求
  const handleImageGeneration = useCallback(async (prompt: string) => {
    if (!imageServiceRef.current || !aiPersonId) {
      // console.error('🖼️ 无法生成图片: 服务未初始化或AI ID不存在');
      console.error('cannot generate image: service not initialized or AI ID not exist');
      return;
    }

    // 设置等待状态
    setWaitingForAIReply?.(true);

    // 生成用户消息的ID和时间戳
    const timestamp = Date.now();
    const userMessageId = `msg_${timestamp}_${Math.random().toString(36).substr(2, 9)}`;
    const aiMessageId = `ai_${timestamp}_${Math.random().toString(36).substr(2, 9)}`;

    // 获取必要的数据用于数据库提交
    let uuid: string | null = null;
    let sessionId: string | undefined = undefined;

    try {
      const userDataStr = localStorage.getItem('userData');
      if (userDataStr) {
        const userData = JSON.parse(userDataStr);
        uuid = userData.visitor_uuid || null;
      }

      // 获取聊天历史中的sessionId
      const chatHistoryStr = localStorage.getItem(`chat_history_${aiPersonId}`);
      if (chatHistoryStr) {
        const chatHistory = JSON.parse(chatHistoryStr);
        sessionId = chatHistory.sessionId;
      }
    } catch (e) {
      console.error('🖼️ 获取用户数据或聊天历史失败:', e);
    }

    // 🔍 添加详细的调试信息
    // console.log('🖼️ 数据检查:', {
    //   uuid: uuid ? '✅ 存在' : '❌ 缺失',
    //   aiPersonId: aiPersonId ? '✅ 存在' : '❌ 缺失',
    //   sessionId: sessionId ? '✅ 存在' : '❌ 缺失',
    //   uuidValue: uuid,
    //   aiPersonIdValue: aiPersonId,
    //   sessionIdValue: sessionId,
    //   isUnmountedRef: isUnmountedRef.current
    // });

    // 构建用户消息对象
    const userMessage = {
      id: userMessageId,
      type: 'text',
      content: prompt,
      sender: 'user',
      timestamp: timestamp,
      status: 'completed'
    };

    // 先在聊天界面添加用户消息（本地添加，不发送API请求）
    if (onAddLocalMessage) {
      addLocalMessage({
        id: userMessageId,
        type: 'text',
        content: prompt,
        sender: 'user',
        timestamp,
        status: 'completed'
      });
    } else {
      // 如果没有提供onAddLocalMessage，则回退到使用onSendMessage
      // 但这会导致额外的API调用
      // console.warn('🖼️ 没有提供onAddLocalMessage，图片生成过程将不显示在聊天界面');
      console.error('no onAddLocalMessage provided, image generation process will not be displayed in the chat interface');
    }

    // 🪙 然后预留tokens
    let reserveId: string;
    try {
      reserveId = await reserveTokensForImage();
    } catch (error) {
      console.error('图片生成token预留失败:', error);

      // 清除等待状态
      setWaitingForAIReply?.(false);

      // 检查是否是余额不足错误
      if ((error as any).isInsufficientTokens) {
        setTokenModalData({
          currentBalance: (error as any).currentBalance,
          required: (error as any).required,
          serviceType: (error as any).serviceType
        });
        setShowTokenModal(true);
        return;
      }

      // 显示错误消息到聊天界面
      if (onAddLocalMessage) {
        addLocalMessage({
          id: aiMessageId, // 使用相同的消息ID，更新现有消息
          type: 'image',
          content: `${t('chat.tokenReservationFailed')}: ${error instanceof Error ? error.message : t('chat.unknownError')}`,
          sender: 'ai',
          timestamp: timestamp + 100,
          receivedAt: Date.now(),
          status: 'failed', // 更新状态为失败
          isImageGenerating: false // 清除图片生成标识
        });
      }
      return;
    }

    try {
      // console.log('🖼️ 开始生成图片:', prompt);

      // 将用户的输入内容提交到数据库
      // if (uuid && aiPersonId) {
      //   try {
      //     const res = await request.post('/api/chat/UpData-ChatHistoryMessage', {
      //       uuid: uuid,
      //       id: aiPersonId,
      //       messages: [userMessage],
      //       sessionId: sessionId,
      //     });

      //     if (res.data.success === true) {
      //       console.log('🖼️ 用户图片生成请求已同步到数据库');
      //     } else {
      //       console.error('🖼️ 用户图片生成请求同步到数据库失败:', res.data);
      //     }
      //   } catch (dbError) {
      //     console.error('🖼️ 数据库同步请求失败:', dbError);
      //   }
      // } else {
      //   console.warn('🖼️ 缺少uuid或aiPersonId，跳过数据库同步');
      // }

      // 添加AI的"正在处理"消息 - 使用图片类型和特殊状态
      if (onAddLocalMessage) {
        addLocalMessage({
          id: aiMessageId,
          type: 'image',
          // content: '正在生成图片，请稍候...',
          sender: 'ai',
          timestamp: timestamp + 100,
          receivedAt: timestamp + 100,
          status: 'sending',
          isImageGenerating: true, // 标记为图片生成中
          // loadingText: '正在根据您的描述生成图片，请稍候...'
        });
      }

      // 发送创建图片请求（不再传递aiPersonId，ImageService会自动从sessionStorage获取）
      const createResponse = await imageServiceRef.current.createImage(prompt, undefined, reserveId);

      // 获取任务ID
      const taskId = createResponse.task_id;
      if (!taskId) {
        throw new Error('未获取到任务ID');
      }

      // console.log(`🖼️ 已创建图片任务 (${taskId}), 预计完成时间: ${createResponse.estimated_time || '未知'}秒`);

      // 轮询任务状态
      const taskResult = await imageServiceRef.current.pollTaskStatus(taskId);

      // 🔄 关键修复：严格检查组件和页面状态
      if (isUnmountedRef.current) {
        // console.log('🔄 组件已卸载，停止处理图片生成结果');
        // 如果有结果，保存到正确的聊天历史
        if (taskResult && taskResult.image_url && aiPersonId) {
          await saveImageToCorrectChatHistory(taskResult, aiPersonId, aiMessageId);
        }
        return;
      }

      // 检查当前页面是否还是原来的页面
      const currentUrl = window.location.pathname;
      const isConversationPage = currentUrl === '/conversation';
      const currentPageId = isConversationPage ? sessionStorage.getItem('currentConversationId') : null;
      if (currentPageId !== aiPersonId) {
        // console.log('🔄 页面已切换，保存图片到正确的聊天历史', {
        //   currentPageId,
        //   originalPageId: aiPersonId,
        //   currentUrl
        // });
        // 保存到正确的聊天历史
        if (taskResult && taskResult.image_url && aiPersonId) {
          await saveImageToCorrectChatHistory(taskResult, aiPersonId, aiMessageId);
        }
        // 清除当前页面的loading状态
        setWaitingForAIReply?.(false);
        return;
      }

      // 🔄 检查ImageService返回的结果
      if (taskResult === null) {
        // ImageService检测到页面已切换，图片已自动保存
        // console.log('🔄 ImageService检测到页面切换，图片已保存到正确位置');
        setWaitingForAIReply?.(false);
        return;
      }

      // 更新AI消息为完成状态并显示图片
      if (taskResult && taskResult.image_url) {
        // 最后一次检查：确保组件没有在处理过程中被卸载
        if (isUnmountedRef.current) {
          // console.log('🔄 处理过程中组件被卸载，保存到正确位置');
          await saveImageToCorrectChatHistory(taskResult, aiPersonId, aiMessageId);
          return;
        }

        if (onAddLocalMessage) {
          // 更新AI消息为图片类型，保持isImageGenerating标识
          addLocalMessage({
            id: aiMessageId,
            type: 'image',
            content: '生成的图片',
            sender: 'ai',
            timestamp: Date.now(),
            status: 'completed',
            imageUrl: taskResult.image_url,
            receivedAt: Date.now(),
            isImageGenerating: true // 标识为新生成的图片
          });

          // 异步处理OSS上传和数据库保存，不影响图片显示
          (async () => {
            try {
              // 检查组件是否已卸载
              // if (isUnmountedRef.current) {
              //   console.log('🖼️ 组件已卸载，取消OSS上传操作');
              //   return;
              // }

              // 先把获取到的图片转存到oss
              // const resPones = await request.post('/api/oss/upload-image-from-url', {
              //   "task_id": taskResult.task_id,
              //   "imageUrl": taskResult.image_url,
              //   "fileName": uuid + "_" + aiPersonId + "_" + Date.now() + '.png'
              // });

              // 再次检查组件是否已卸载
              // if (isUnmountedRef.current) {
              //   console.log('🖼️ 组件已卸载，取消数据库保存操作');
              //   return;
              // }

              // if (resPones.data.success === true) {
              //   // 将数据存储到数据库
              //   const res = await request.post('/api/chat/UpData-ChatHistoryMessage', {
              //     uuid: uuid,
              //     id: aiPersonId,
              //     messages: [{
              //       id: aiMessageId,
              //       type: 'image',
              //       content: '生成的图片',
              //       sender: 'ai',
              //       timestamp: Date.now(),
              //       status: 'completed',
              //       imageUrl: resPones.data.customUrl,
              //       receivedAt: Date.now()
              //     }],
              //     sessionId: sessionId,
              //   });

              //   console.log('🖼️ 图片已保存到OSS和数据库:', resPones.data.customUrl);
              // } else {
              //   console.warn('🖼️ OSS上传失败，但图片已成功显示:', resPones.data);
              // }
            } catch (saveError) {
              // 检查是否因为组件卸载导致的错误
              if (isUnmountedRef.current) {
                // console.log('🖼️ 组件已卸载，忽略保存错误');
                return;
              }
              // console.error('🖼️ 保存图片到OSS或数据库失败，但图片已成功显示:', saveError);
              console.error('save image to oss or database failed, but image is successfully displayed', saveError);
              // 这里不抛出错误，避免影响用户看到图片
            }
          })();

        } else {
          // 如果没有提供onAddLocalMessage，则回退到使用onSendMessage
          // onSendMessage(`[图片已生成] ${taskResult.image_url}`, false);
          onSendMessage(`[image generated] ${taskResult.image_url}`, false);
        }

        // 记录图片生成的详细信息
        // console.log('🖼️ 图片生成成功:', {
        //   imageUrl: taskResult.image_url,
        //   userPrompt: taskResult.user_prompt,
        //   refinedPrompt: taskResult.refined_prompt,
        //   processingTime: taskResult.total_processing_time
        // });
      }

      // 图片生成成功，清除等待状态
      setWaitingForAIReply?.(false);

    } catch (error) {
      // console.error('🖼️ 图片生成失败:', error);
      console.error('image generation failed', error);

      // 图片生成失败，清除等待状态
      setWaitingForAIReply?.(false);

      // 更新之前创建的loading消息状态为失败，而不是添加新的错误消息
      if (onAddLocalMessage) {
        addLocalMessage({
          id: aiMessageId, // 使用相同的消息ID，更新现有消息
          type: 'image',
          content: `${t('chat.imageGenerationFailed')}: ${error instanceof Error ? error.message : t('chat.unknownError')}`,
          sender: 'ai',
          timestamp: timestamp + 100,
          receivedAt: Date.now(),
          status: 'failed', // 更新状态为失败
          isImageGenerating: false // 清除图片生成标识
        });
      } else {
        // 如果没有提供onAddLocalMessage，则回退到使用onSendMessage
        onSendMessage(`${t('chat.imageGenerationFailed')}: ${error instanceof Error ? error.message : t('chat.unknownError')}`, isVoiceMode);
      }
    }
  }, [aiPersonId, isVoiceMode, onSendMessage, onAddLocalMessage, addLocalMessage, reserveTokensForImage, setWaitingForAIReply]);

  // 处理发送消息 - 使用useCallback优化
  const handleSendMessage = useCallback(() => {
    const trimmedValue = inputValue.trim();
    if (trimmedValue && !disabled) {
      // 判断是否为图片生成模式
      if (isImageGenerationMode && originalPrompt) {
        if (trimmedValue === originalPrompt) {
          // 用户没有修改初始提示词，启动图片生成流程
          // 立即清空输入框，提升用户体验
          setInputValue('');
          setIsImageGenerationMode(false);
          setOriginalPrompt('');

          // 重置输入框高度
          if (textareaRef.current) {
            textareaRef.current.style.height = 'auto';
          }

          handleImageGeneration(trimmedValue);
          return; // 避免继续执行后续代码
        } else if (trimmedValue.startsWith(originalPrompt)) {
          // console.log('🖼️ 用户选中了图片生成功能并添加了描述');
          // 用户在提示词基础上添加了描述，也应使用图片生成功能
          // 立即清空输入框，提升用户体验
          setInputValue('');
          setIsImageGenerationMode(false);
          setOriginalPrompt('');

          // 重置输入框高度
          if (textareaRef.current) {
            textareaRef.current.style.height = 'auto';
          }

          handleImageGeneration(trimmedValue);
          return; // 避免继续执行后续代码
        } else {
          // 用户完全修改了提示词，按普通聊天模式处理
          onSendMessage(trimmedValue, isVoiceMode);
        }
      }
      else {
        // 普通聊天模式
        onSendMessage(trimmedValue, isVoiceMode);
      }

      // 重置状态 (只有在直接调用onSendMessage的情况下才重置)
      setInputValue('');
      setIsImageGenerationMode(false);
      setOriginalPrompt('');

      // 重置输入框高度
      if (textareaRef.current) {
        textareaRef.current.style.height = 'auto';
      }
    }
  }, [inputValue, disabled, onSendMessage, isVoiceMode, isImageGenerationMode, originalPrompt, handleImageGeneration]);

  // 处理下拉选项点击
  const handleDropdownOptionClick = useCallback((option: string) => {
    if (option === t('chat.messageInput.imageGeneration.howToUse')) {
      setShowHowToUseModal(true);
      // 点击How to Use时，不关闭下拉框，保持显示状态
    } else {
      // 图片生成选项
      setInputValue(option);
      setIsImageGenerationMode(true);
      setOriginalPrompt(option);

      // 设置光标到文本末尾
      setTimeout(() => {
        if (textareaRef.current) {
          textareaRef.current.focus();
          textareaRef.current.selectionStart = option.length;
          textareaRef.current.selectionEnd = option.length;
        }
        adjustTextareaHeight();
      }, 0);

      // console.log('🖼️ 用户选择了图片生成选项:', option);
      // 只有选择图片生成选项时才关闭下拉框
      setShowDropdown(false);
    }
  }, [adjustTextareaHeight, t]);

  // 切换下拉菜单显示
  const toggleDropdown = useCallback(() => {
    setShowDropdown(prev => !prev);
  }, []);

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        // 如果教程弹窗正在显示，不关闭下拉框
        if (!showHowToUseModal) {
          setShowDropdown(false);
        }
      }
    };

    if (showDropdown) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showDropdown, showHowToUseModal]);

  // 切换输入模式 - 使用useCallback优化
  const toggleInputMode = useCallback(async () => {
    if (!isMobile) return; // 只在移动端支持切换

    // 如果是切换到录音模式，先预检麦克风权限
    if (!isVoiceInputMode) {
      // console.log('🎤 切换到录音模式 - 开始预检麦克风权限');

      try {
        const micResult = await AudioCompatibility.testMicrophoneAccess();

        if (!micResult.hasPermission) {
          // console.error('🎤 麦克风权限预检失败:', micResult.error);
          // 权限被拒绝，显示友好提示但仍然切换到录音模式（让用户后续可以重试）
          setPermissionError(micResult.error || t('chat.micPermissionFailed'));
        } else {
          // console.log('🎤 麦克风权限预检成功，切换到录音模式');
          setPermissionError(null); // 清除之前的错误
        }
      } catch (error) {
        // console.error('🎤 麦克风权限预检异常:', error);
        // 预检失败也允许切换，让用户后续可以重试
        setPermissionError(t('chat.micPermissionCheck'));
      }
    }

    setIsVoiceInputMode(prev => !prev);
  }, [isMobile, isVoiceInputMode]);

  // 处理语音输入结果 - 使用useCallback优化
  const handleVoiceResult = useCallback((text: string) => {
    // console.log('🎤 MessageInput收到最终语音识别结果:', text);

    if (isMobile && isVoiceInputMode) {
      // 移动端语音模式：用户松开按钮后的最终结果，直接发送消息并保持在录音模式
      // console.log('🎤 移动端语音模式 - 自动发送消息并保持录音模式');
      if (text.trim()) {
        onSendMessage(text.trim(), isVoiceMode);
        // 录音成功，清除权限错误提示
        setPermissionError(null);
        // 保持在录音模式，不自动切换
      }
    } else {
      // PC端或输入框模式：将语音识别的文本填充到输入框
      // console.log('🎤 PC端或输入框模式 - 填充到输入框');
      setInputValue(text);
      // 调整输入框高度
      setTimeout(() => {
        adjustTextareaHeight();
        // 将光标移动到文本末尾
        if (textareaRef.current) {
          textareaRef.current.selectionStart = text.length;
          textareaRef.current.selectionEnd = text.length;
        }
      }, 0);
    }
  }, [adjustTextareaHeight, isMobile, isVoiceInputMode, onSendMessage, isVoiceMode]);

  // 处理语音识别错误 - 使用useCallback优化
  const handleVoiceError = useCallback((error: string) => {
    console.error('🎤 语音识别错误:', error);
    // 这里可以显示错误提示，暂时只在控制台输出
  }, []);

  // 处理键盘事件 - 使用useCallback优化
  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  }, [handleSendMessage]);

  // 移动端软键盘处理 - 优化防抖
  useEffect(() => {
    let timeoutId: NodeJS.Timeout;

    const handleResize = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        if (isFocused && textareaRef.current) {
          textareaRef.current.scrollIntoView({
            behavior: 'smooth',
            block: 'nearest'
          });
        }
      }, 300);
    };

    window.addEventListener('resize', handleResize, { passive: true });
    return () => {
      clearTimeout(timeoutId);
      window.removeEventListener('resize', handleResize);
    };
  }, [isFocused]);

  // 计算占位符文本 - 使用useMemo优化
  const placeholder = useMemo(() =>
    isVoiceMode ? t('chat.inputMessageVoice') : t('chat.inputMessage'),
    [isVoiceMode, t]
  );

  // 计算发送按钮状态 - 使用useMemo优化
  const isButtonDisabled = useMemo(() =>
    disabled || !inputValue.trim(),
    [disabled, inputValue]
  );

  // 切换语音模式
  const handleToggleVoiceMode = () => {
    setIsVoiceMode(prev => !prev);
  };

  return (
    <div className="bg-[rgb(19,19,19)] p-4">
      {/* 包裹输入框和发送按钮的盒子  */}
      <div
        className=" items-center  md:max-w-[50rem] w-full mx-auto"
      >
        {/* 第一排按钮存放处  */}
        <div className='flex mb-2'>
          {/* 语音模式的按钮  */}
          <>
            <div
              onClick={handleToggleVoiceMode}
              style={{
                border: isVoiceMode ? '1px solid rgb(236,72,153)' : '1px solid rgb(129,65,230)',
                backgroundColor: isVoiceMode ? 'rgba(236,72,153,0.1)' : 'rgb(49,34,71)',
                color: isVoiceMode ? 'rgb(236,72,153)' : 'rgb(255,255,255,0.9)',
                fontFamily: dynamicFonts.font1,
                fontSize: "0.9rem"
              }}
              className='px-2 py-1 rounded-xl cursor-pointer flex items-center space-x-2 transition-all duration-200 select-none'
            >
              <img className='w-5 h-5 mr-1' src={isVoiceMode ? openVoiceIcon : closeVoiceIcon} alt={isVoiceMode ? "closeVoice" : "openVoice"} />
              {isVoiceMode ? t('chat.closeVoice') : t('chat.openVoice')}
            </div>
          </>
          {/* MBTI测试按钮，仅id为20时显示 */}

        </div>
        {/* 第二排按钮存放处  */}
        <div className="flex items-center space-x-3 w-full mx-auto">
          {/* 切换按钮 - 仅在移动端显示 */}
          {isMobile && (
            <button
              onClick={toggleInputMode}
              disabled={disabled}
              className="flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center bg-gray-600 text-white hover:bg-gray-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              title={isVoiceInputMode ? t('chat.switchToText') : t('chat.switchToVoice')}
            >
              <i className={`fas ${isVoiceInputMode ? 'fa-keyboard' : 'fa-microphone'} text-sm`}></i>
            </button>
          )}

          {/* PC端语音输入按钮 - 仅在PC端显示 */}
          {!isMobile && (
            <VoiceInputButton
              onResult={handleVoiceResult}
              onError={handleVoiceError}
              disabled={disabled}
              size="small"
              variant="button"
            />
          )}

          {/* 输入框和大尺寸语音按钮的容器 */}
          <div className="flex-1 relative">
            {isMobile && isVoiceInputMode ? (
              /* 移动端大尺寸语音按钮 */
              <>
                <VoiceInputButton
                  onResult={handleVoiceResult}
                  onError={handleVoiceError}
                  disabled={disabled}
                  size="large"
                  variant="input"
                />
                {/* 权限错误提示 */}
                {permissionError && (
                  <div className="absolute top-full left-0 right-0 mt-2 p-3 bg-red-600 text-white text-sm rounded-lg shadow-lg z-10">
                    <div className="flex items-start space-x-2">
                      <i className="fas fa-exclamation-triangle text-yellow-400 mt-0.5 flex-shrink-0"></i>
                      <div className="flex-1">
                        <div className="font-medium mb-1">{t('chat.micPermissionTitle')}</div>
                        <div className="text-red-100">{permissionError}</div>
                        <button
                          onClick={() => setPermissionError(null)}
                          className="mt-2 text-xs text-red-200 hover:text-white underline"
                        >
                          {t('chat.gotIt')}
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </>
            ) : (
              /* 输入框容器 */
              <div className="relative w-full flex justify-center">
                <textarea
                  ref={textareaRef}
                  value={inputValue}
                  onChange={handleInputChange}
                  onKeyDown={handleKeyDown}
                  onFocus={handleFocus}
                  onBlur={handleBlur}
                  placeholder={placeholder}
                  disabled={disabled}
                  className="w-full px-4 py-3 pr-[6.5rem] bg-gray-700 text-white rounded-2xl resize-none focus:outline-none focus:ring-2 focus:ring-pink-500 placeholder-gray-400 min-h-[48px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed"
                  style={{
                    lineHeight: '1.5',
                    // 避免iOS Safari的zoom问题
                    fontSize: '16px'
                  }}
                  rows={1}
                />

                {/* 下拉选择器按钮 - 位于输入框内右侧 */}
                <div style={{ fontFamily: dynamicFonts.font3 }} className="absolute right-1 top-[0.35rem] flex items-center" ref={dropdownRef}>
                  <button
                    onClick={toggleDropdown}
                    disabled={disabled}
                    className={`py-2 px-4 rounded-3xl flex items-center justify-center text-gray-300 hover:text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${showDropdown
                      ? 'border border-[rgb(90,68,230)] bg-[rgb(29,30,54)]'
                      : 'bg-gray-600 hover:bg-gray-500'
                      }`}
                    style={{ minWidth: '5.5rem' }}
                    title={t('chat.messageInput.imageGeneration.ask')}
                  >
                    <i className="fas fa-image text-[0.9rem]"></i>
                    <span className="ml-2 text-[0.9rem]">{t('chat.messageInput.imageGeneration.ask')}</span>
                    <i className={`fas ${showDropdown ? 'fa-chevron-up' : 'fa-chevron-down'} text-[0.8rem] ml-2`}></i>
                  </button>

                  {/* 下拉选项列表 */}
                  {showDropdown && (
                    <div
                      className="absolute bottom-full left-[0rem] mb-2 rounded-2xl shadow-lg py-2 min-w-[140px] z-20"
                      style={{
                        backgroundColor: 'rgb(29, 30, 54)',
                        borderColor: 'rgb(89, 68, 230)',
                        borderWidth: '1px',
                        borderStyle: 'solid'
                      }}
                    >
                      {DROPDOWN_OPTIONS.map((option, index) => (
                        <button
                          key={index}
                          onClick={() => handleDropdownOptionClick(option)}
                          className="w-full px-4 py-2 text-center text-white hover:bg-opacity-80 transition-colors text-sm border-b border-gray-500 last:border-b-0 flex items-center justify-center space-x-1"
                          style={{
                            backgroundColor: 'transparent'
                          }}
                        >
                          {option === t('chat.messageInput.imageGeneration.howToUse') && (
                            <i className="fas fa-question-circle text-xs"></i>
                          )}
                          <span>{option}</span>
                        </button>
                      ))}
                    </div>
                  )}

                  {/* 教程弹窗在PC端时渲染在下拉框容器内 */}
                  {showHowToUseModal && !isMobile && (
                    <div>
                      <HowToUseModal
                        show={showHowToUseModal}
                        onClose={() => {
                          setShowHowToUseModal(false);
                          // 关闭教程弹窗时，不关闭下拉框，保持下拉框显示状态
                        }}
                        dropdownRef={dropdownRef}
                      />
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>


          {/* 发送按钮 - 仅在非语音模式显示 */}
          {!(isMobile && isVoiceInputMode) && (
            // 移动端：仅当有内容时显示发送按钮，PC端始终显示
            (!isMobile || inputValue.trim()) && (
              <button
                onClick={handleSendMessage}
                disabled={isButtonDisabled}
                className={`flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center transition-colors ${isButtonDisabled
                  ? 'bg-gray-600 text-gray-400 cursor-not-allowed'
                  : 'bg-pink-500 text-white hover:bg-pink-600'
                  }`}
              >
                <i className="fas fa-paper-plane text-sm"></i>
              </button>
            )
          )}
        </div>

      </div>

      {/* 移动端教程弹窗 - 渲染在组件根级别 */}
      {showHowToUseModal && isMobile && (
        <HowToUseModal
          show={showHowToUseModal}
          onClose={() => {
            setShowHowToUseModal(false);
          }}
          dropdownRef={dropdownRef}
        />
      )}

      {/* Token不足弹窗 */}
      <TokenInsufficientModal
        show={showTokenModal}
        onClose={() => setShowTokenModal(false)}
        currentBalance={tokenModalData.currentBalance}
        required={tokenModalData.required}
        serviceType={tokenModalData.serviceType}
      />
    </div>
  );
});

// 显示名称用于调试
MessageInput.displayName = 'MessageInput';

export default MessageInput; 